package com.qlhx.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qlhx.common.model.ApiResult;
import com.qlhx.model.Key;
import com.qlhx.service.KeyService;

import io.swagger.annotations.Api;

@Api(value = "凭证接口", description = "凭证接口")
@CrossOrigin(maxAge = 3600)
@RestController
@Scope(value = "prototype") 
@RequestMapping("key")
public class KeyController {
	
	private  final Logger logger = LoggerFactory.getLogger(KeyController.class);
	
	
	@Autowired
	KeyService keyService;
	
	@RequestMapping(value = "list", method = RequestMethod.POST ,produces = { "application/json" })
	public @ResponseBody List<Key> list() {

		List<Key> list = keyService.list();
		return list;
	}
	
	
	@RequestMapping(value = "addOrUpdate", method = RequestMethod.POST, produces = { "application/json" })
	public @ResponseBody ApiResult<String> addOrUpdate(Key key, HttpServletRequest request) {
		ApiResult<String> result = new ApiResult<String>();
		String biometricsValue = "0000000000000000";
		String cardValue = "0000000000000000";
		String[] biometricsArr = key.getBiometrics().split(",");
		for(String biometrics : biometricsArr)
		{
			biometricsValue = replaceString(biometricsValue,"1",Integer.parseInt(biometrics));
		}
		
		String[] cardArr = key.getCard().split(",");
		for(String card : cardArr)
		{
			cardValue = replaceString(cardValue,"1",Integer.parseInt(card));
		}
		
		key.setBiometrics(biometricsValue);
		key.setCard(cardValue);
		key.setCreatedate(new Date());
		keyService.insertSelective(key);
		return result;
	}
	
//	public static void main(String[] args) {
//		String biometricsValue = "0000000000000000";
//		biometricsValue =  replaceString(biometricsValue,"1",1);
//		biometricsValue =  replaceString(biometricsValue,"1",5);
//        System.out.println(biometricsValue);
//    }
	
    public static String replaceString(String str, String rstr, int a) {
        return str.substring(0, a - 1) + rstr + str.substring(a);
    }

}
